<?php

namespace app\admin\model;

use app\model\Model;

class Chip extends Model
{
  public $privilege = 'chip';
  public $cids;
  public $id;
  public $db;

  function __construct()
  {
    include 'check.php';
    new Check();

    $this->db = $GLOBALS['db'];
    $this->cids = checkAdminPriv(@$this->privilege); // 判断权限
    $this->id = intval($_GET['id']);
  }

  function index()
  {
    include_once LIB_PATH . 'cls.page.php';

    $pager = new \Page(ADMIN_PAGE_SIZE);
    $pager->handle($GLOBALS['db']->getOne("SELECT COUNT(*) FROM chip"));

    $this->tpl('chip', [
      'db' => $this->db,
      'list' => $GLOBALS['db']->getAll("SELECT * FROM chip ORDER BY id DESC LIMIT " . $pager->page_start . "," . $pager->page_size),
      'pager' => $pager,
    ]);
  }

  function add()
  {
    $data = get_post(['c_content']);

    if ($id = $GLOBALS['db']->exec("INSERT INTO chip " . arr_insert($data))) {
      \admin_log('碎片新增 [id:' . $id . ']');
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'chip'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function edit()
  {
    $row = $GLOBALS['db']->getRow("SELECT * FROM chip WHERE id = $this->id");
    $this->tpl('chip_edit', [
      'db' => $this->db,
      'row' => $row,
    ]);
  }

  function edit_action()
  {
    $data = get_post(['c_content']);

    if ($GLOBALS['db']->exec("UPDATE chip SET " . arr_update($data) . " WHERE id = $this->id")) {
      \admin_log("碎片编辑 [id:$this->id]");
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'chip'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function del()
  {
    $res = $GLOBALS['db']->getRow("SELECT * FROM chip WHERE id = '" . $this->id . "'");

    if ($res['c_safe']) {
      alert_back('已受保护,无法删除！');
    }

    if ($GLOBALS['db']->exec("DELETE FROM chip WHERE id = $this->id")) {
      \admin_log("碎片删除 [id:$this->id]");
      alert_href($GLOBALS['lang']['msg_success'], M('admin', 'chip'));
    }

    alert_back($GLOBALS['lang']['msg_tryagain']);
  }

  function __destruct()
  {
  }
}